{% extends 'base.html' %}

<!--头部样式-->
{% block head %}
<style>
    :root {
        --primary-color: #4361ee;
        --secondary-color: #f8f9fa;
        --accent-color: #3a0ca3;
        --border-radius: 8px;
    }

    /*body {*/
    /*    background-color: #f8fafc;*/
    /*    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;*/
    /*    padding: 20px;*/
    /*}*/

    .main-container {
        max-width: 1200px;
        margin: 0 auto;
    }

    .form-container {
        background: white;
        border-radius: 12px;
        box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
        padding: 2rem;
        margin-top: 2rem;
    }

    .form-header {
        border-bottom: 1px solid #eaeaea;
        padding-bottom: 1.2rem;
        margin-bottom: 1.5rem;
    }

    .form-label {
        color: #495057;
        font-weight: 600;
        margin-bottom: 0.5rem;
        font-size: 0.95rem;
    }

    .form-control, .form-select {
        border-radius: var(--border-radius);
        border: 1px solid #dee2e6;
        padding: 0.75rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.15);
    }

    .form-control-sm {
        padding: 0.6rem 0.75rem;
    }

    .btn-group .btn {
        border-radius: var(--border-radius);
        transition: all 0.2s ease;
        padding: 0.6rem 0;
    }

    .btn-outline-primary {
        color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .btn-outline-primary:hover, .btn-check:checked + .btn-outline-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        border-radius: var(--border-radius);
        padding: 0.75rem 1.5rem;
        font-weight: 600;
    }

    .btn-primary:hover {
        background-color: var(--accent-color);
        border-color: var(--accent-color);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(58, 12, 163, 0.2);
    }

    .btn-outline-secondary {
        border-radius: var(--border-radius);
        padding: 0.75rem 1.5rem;
        font-weight: 600;
    }

    .btn-outline-secondary:hover {
        background-color: #6c757d;
        color: white;
        transform: translateY(-2px);
    }

    .form-section {
        margin-bottom: 1.5rem;
        position: relative;
        transition: transform 0.2s ease;
    }

    .form-section:hover {
        transform: translateY(-3px);
    }

    .input-group .btn {
        border-radius: 0 var(--border-radius) var(--border-radius) 0;
    }

    .footer-actions {
        border-top: 1px solid #eaeaea;
        padding-top: 1.5rem;
        margin-top: 1rem;
    }

    @media (max-width: 992px) {
        .btn-group {
            width: 100% !important;
        }

        .d-flex.justify-content-end {
            justify-content: flex-start !important;
        }

        .footer-actions .d-flex {
            flex-direction: column;
            gap: 10px;
        }

        .footer-actions .btn {
            width: 100%;
        }
    }

    .icon-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 30px;
        background: rgba(67, 97, 238, 0.1);
        border-radius: 50%;
        margin-right: 8px;
    }


</style>
{% endblock head %}


<!--登录信息替换-->
{% block login_info %}
<div>
    <ul class="navbar-nav me-auto mb-2 mb-lg-0 clearfix">
        <li class="nav-item" style="margin: 0 10px">
            <a class="nav-link" aria-current="page" href="{{url_for('post.user_center')}}">管理中心</a>
        </li>
        <li class="nav-item" style="margin: 0 10px">
            <a class="nav-link" aria-current="page" href="#" data-bs-toggle="modal" data-bs-target="#staticBackdrop">欢迎你：豪哥</a>
        </li>
    </ul>
</div>
{% endblock login_info %}

<!--中间替换为编辑器-->
{% block bodyMiddle %}
<div class="editor">
    <!-- 发布信息 -->

    <div class="main-container">
        <div class="form-container">
            <div class="form-header">
                <h4 class="mb-0"><i class="fa-solid fa-pen-to-square"></i>发布文章</h4>
                <!--                <p class="text-muted mt-2">填写以下信息发布您的文章</p>-->
                <div style="padding: 15px 0"><input class="form-control" type="text" name="article-headline"
                                                    placeholder="标题"
                                                    id="article-headline" style="height: 50px"></div>
                <div class="col-12">
                    <!--引入ueditor,结合下边的js文件-->
                    <script id="editor" type="text/plain" class="editor-content"></script>
                </div>
            </div>

            <div class="row g-4">
                <!-- 类型 -->
                <div class="col-12 col-md-6 col-lg-4">
                    <div class="form-section">
                        <label class="form-label"><span class="icon-badge"><i class="fa-solid fa-tags"></i></span>文章类型</label>
                        <select class="form-select form-select-sm" id="articletype">
                            <option value="0" selected>请选择文章类型</option>
                            {% for k,v in article_type.items() %}
                            <option value={{k}}>{{v}}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>

                <!-- 积分 -->
                <div class="col-12 col-md-6 col-lg-3">
                    <div class="form-section">
                        <label class="form-label"><span class="icon-badge"><i class="fa-solid fa-coins"></i></span>积分设置</label>
                        <select class="form-select form-select-sm" id="credit_coin">
                            <option value="0" selected>0 积分</option>
                            <option value="1">1 积分</option>
                            <option value="2">2 积分</option>
                            <option value="3">3 积分</option>
                            <option value="5">5 积分</option>
                            <option value="10">10 积分</option>
                        </select>
                    </div>
                </div>

                <!-- 分类 -->
                <div class="col-12 col-md-6 col-lg-3">
                    <div class="form-section">
                        <label class="form-label"><span class="icon-badge"><i
                                class="fa-solid fa-bars-staggered"></i></span>标签合集</label>
                        <div class="input-group">
                            <input class="form-control form-control-sm" type="text" placeholder="选择标签合集"
                                   id="article_tags" readonly>
                            <button class="btn btn-outline-secondary btn-sm" type="button">
                                <i class="fa-regular fa-folder-open"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 访问权限 -->
                <div class="col-12 col-md-6 col-lg-2">
                    <div class="form-section">
                        <label class="form-label"><span class="icon-badge"><i class="fa-solid fa-unlock"></i></span>访问权限</label>
                        <div class="btn-group btn-group-sm w-100" role="group">
                            <input type="radio" value="1" class="btn-check" name="access" id="public" checked>
                            <label class="btn btn-outline-primary" for="public">公开</label>

                            <input type="radio" value="0" class="btn-check" name="access" id="private">
                            <label class="btn btn-outline-primary" for="private">仅个人</label>
                        </div>
                    </div>
                </div>

                <!-- 按钮组 -->
                <div class="col-12">
                    <div class="footer-actions">
                        <div class="d-flex justify-content-end gap-3">
                            <button class="btn btn-outline-secondary" onclick="articleDraft()">
                                <i class="fa fa-book-bookmark"></i>保存为草稿
                            </button>
                            <button class="btn btn-primary" onclick="articlePost()">
                                <i class="fa-regular fa-paper-plane"></i>发布文章
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 额外的信息提示 -->
        <div class="row mt-4" style="margin-bottom: 50px">
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa-solid fa-lightbulb"></i>发布指南</h5>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item">1. 选择适当的文章类型有助于读者发现您的内容</li>
                            <li class="list-group-item">2. 设置积分奖励可以激励更多互动</li>
                            <li class="list-group-item">3. 将文章添加到合适的合集便于组织内容</li>
                            <li class="list-group-item">4. 发布前请仔细检查文章内容</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa-regular fa-chart-bar"></i>数据统计</h5>
                        <div class="d-flex justify-content-around text-center mt-4">
                            <div>
                                <h3 class="text-primary">24</h3>
                                <p class="text-muted">已发布文章</p>
                            </div>
                            <div>
                                <h3 class="text-primary">1,358</h3>
                                <p class="text-muted">总阅读量</p>
                            </div>
                            <div>
                                <h3 class="text-primary">87</h3>
                                <p class="text-muted">获得点赞</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock bodyMiddle %}


<!--引入uedior编辑器-->
{% block footjs %}
<script type="text/javascript" src="../static/ueditor/ueditor-plus/dist-min/ueditor.config.js"></script>
<script type="text/javascript" src="../static/ueditor/ueditor-plus/dist-min/ueditor.all.js"></script>
<script type="text/javascript" src="../static/ueditor/ueditor-plus/dist-min/lang/zh-cn/zh-cn.js"></script>
<script>
    var ue = UE.getEditor('editor', {
        initialFrameHeight: 500,
        initialFrameWidth: 1136,
        serverUrl: "/ueditor",
        // toolbars:[["fullscreen","source","|",]],//定义有哪些按键
        // toolbarShow: {// 这样就控制即使在 toolbars 中配置了该功能，也不显示
        //     "attachment": false,
        // },
        ai: {
            driver: 'Ollama',//ai.js文件中添加了ollama这个平台
            driverConfig: {
                url: 'http://localhost:11434/v1/chat/completions',
                key: '', // 本地 Ollama 不需要 key，但字段必须存在，
                model: 'deepseek-r1:8b'
            }
        },

        // 功能按钮保持官方示例即可
        aiFunctions: [
            {
                text: '<i class="edui-iconfont edui-icon-translate"></i> 翻译',
                prompt: "{selectText}\n\n请帮我翻译一下这段内容，并直接返回优化后的结果。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回英文，如果是英文，请给我返回中文内容，只需要返回内容即可，不需要告知我是中文还是英文。",
                enable: function (param) {
                    return !!param.selectText;
                }
            },
            {
                text: '<i class="edui-iconfont edui-icon-continue-write"></i> 续写',
                prompt: "{selectText}\n\n请帮我续写一下这段内容，并直接返回续写后的结果。",
                enable: function (param) {
                    return !!param.selectText;
                }
            },
            {
                text: '<i class="edui-iconfont edui-icon-text-shrink"></i> 简化内容',
                prompt: "{selectText}\n\n请帮我简化一下这段内容，并直接返回简化后的结果。",
                enable: function (param) {
                    return !!param.selectText;
                }
            },
            {
                text: '<i class="edui-iconfont edui-icon-text-extend"></i> 丰富内容',
                prompt: "{selectText}\n\n请帮我丰富一下这段内容，并直接返回丰富后的结果。",
                enable: function (param) {
                    return !!param.selectText;
                }
            }
        ]
    });

    // ARTICLEID 是一个全局变量，用于临时存储文章或草稿的 ID。其值在页面未刷新时不会自动重置为 0.生命周期为整个页面为刷新
    var ARTICLEID = 0;

    // 监听文章提交事件
    function articlePost() {
        const headline = document.getElementById('article-headline').value;
        const editorContent = UE.getEditor('editor').getContent();
        const articleType = document.getElementById('articletype').value;
        const creditCoin = document.getElementById('credit_coin').value;
        const access = document.querySelector('input[name="access"]:checked');
        const accessValue = access.value;
        if (!headline.trim() || !editorContent.trim()) {
            alert('文章内容或标题不完整，请补充完善。')
            return false
        } else if (articleType === '0') {
            alert('请选择文章分类后进行提交。')
            return false
        } else {
            fetch('/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "headline": headline.trim(),
                    "content": editorContent.trim(),
                    "type": articleType,
                    "accessible": accessValue,
                    "credit": creditCoin,
                    "drafted": "0",
                    "articleid": ARTICLEID,
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络错误，提交失败！');
                } else {
                    return response.text()
                }
            }).then(data => {
                if (data === "perm-denied") {
                    alert('当前还未登录!')
                } else if (data === 'post-fail') {
                    alert("发生故障，请联系管理员！")
                    console.log('发生故障')
                } else if (data.match(/^\d+$/)){
                    // alert('文章已发布！')
                    var num = parseInt(data, 10)
                    window.location.href = `/article/${num}`
                }else {
                    alert({title: "错误提示", message: "文章发布失败，可能没有权限."});
                }
            }).catch(error => {
                console.log('Error:', error)
            })
        }
    }

    // 草稿
    function articleDraft() {
        const headline = document.getElementById('article-headline').value;
        const editorContent = UE.getEditor('editor').getContent();
        const articleType = document.getElementById('articletype').value;
        console.log(articleType)
        const creditCoin = document.getElementById('credit_coin').value;
        const access = document.querySelector('input[name="access"]:checked');
        const accessValue = access.value;
        if (!headline.trim() || !editorContent.trim()) {
            alert('文章内容或标题不完整，请补充完善。')
            return false
        } else if (articleType === '0') {
            alert('请选择文章分类后进行提交。')
            return false
        } else {
            fetch('/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "headline": headline.trim(),
                    "content": editorContent.trim(),
                    "type": articleType,
                    "accessible": accessValue,
                    "credit": creditCoin,
                    "drafted": "1",
                    "articleid": ARTICLEID,
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络错误，提交失败！');
                } else {
                    return response.text()
                }
            }).then(data => {
                if (data === "perm-denied") {
                    alert('当前还未登录!')
                } else if (data === 'post-fail') {
                    alert("发生故障，请联系管理员！")
                    console.log('发生故障')
                } else if (data.match(/^\d+$/)) {
                    alert('文章草稿已保存！')
                    // 保存草稿后，不跳转页面，重新为全局变量赋值。获得草稿在数据库中的articleid，便于更新
                    ARTICLEID = parseInt(data,10);
                } else {
                    alert({title: "错误提示", message: "保存草稿失败，可能没有权限."});
                }
            }).catch(error => {
                console.log('Error:', error)
            })
        }
    }


</script>
{% endblock footjs %}